<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web 控制台 示例</title>
    <style>
        body {
            font-family: "Courier New", monospace;
            background-color: #2e2e2e;
            color: white;
            margin: 0;
            padding: 0;
            height: 100vh;
        }

        .console-container {
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: center;
            height: 100%;
            padding: 20px;
        }

        .console-output {
            width: 100%;
            height: 80%;
            border: 2px solid #444;
            padding: 10px;
            background-color: #333;
            color: white;
            font-size: 16px;
            overflow-y: auto;
            margin-bottom: 20px;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .input-container {
            width: 100%;
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }

        input[type="text"] {
            flex: 1;
            padding: 10px;
            background-color: #444;
            color: white;
            border: 1px solid #555;
            font-size: 16px;
        }

        .color-select {
            width: 120px;
            position: relative;
            user-select: none;
        }

        .color-select-header {
            padding: 10px;
            background-color: #444;
            border: 1px solid #555;
            color: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .color-select-options {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background-color: #444;
            border: 1px solid #555;
            border-top: none;
            max-height: 200px;
            overflow-y: auto;
            display: none;
            z-index: 1000;
        }

        .color-select.open .color-select-options {
            display: block;
        }

        .color-option {
            padding: 8px 10px;
            cursor: pointer;
        }

        .color-option:hover {
            background-color: #555;
        }

        input[type="text"]:focus {
            outline: none;
            border: 1px solid #00bcd4;
        }

        .console-output span {
            display: block;
            margin: 5px 0;
        }
    </style>
</head>

<body>
    <div class="console-container">
        <div class="console-output" id="consoleOutput"></div>
        <div class="input-container">
            <input type="text" id="consoleInput" placeholder="输入文本内容，用逗号分隔多个参数">
            <div class="color-select" id="colorSelect">
                <div class="color-select-header">
                    <span>选择颜色</span>
                    <span>▼</span>
                </div>
                <div class="color-select-options" id="colorOptions"></div>
            </div>
        </div>
    </div>

    <script>
        const colorize = (...args) => ({
            black: `\x1b[30m${args.join(' ')}\x1b[0m`,
            red: `\x1b[31m${args.join(' ')}\x1b[0m`,
            green: `\x1b[32m${args.join(' ')}\x1b[0m`,
            yellow: `\x1b[33m${args.join(' ')}\x1b[0m`,
            blue: `\x1b[34m${args.join(' ')}\x1b[0m`,
            magenta: `\x1b[35m${args.join(' ')}\x1b[0m`,
            cyan: `\x1b[36m${args.join(' ')}\x1b[0m`,
            white: `\x1b[37m${args.join(' ')}\x1b[0m`,
            bgBlack: `\x1b[40m${args.join(' ')}\x1b[0m`,
            bgRed: `\x1b[41m${args.join(' ')}\x1b[0m`,
            bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`,
            bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`,
            bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`,
            bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`,
            bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`,
            bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m`
        });

        // ANSI 转义码到 CSS 样式的映射
        const ansiToCss = (text) => {
            const colorMap = {
                '\x1b[30m': 'color: black;',
                '\x1b[31m': 'color: red;',
                '\x1b[32m': 'color: green;',
                '\x1b[33m': 'color: yellow;',
                '\x1b[34m': 'color: blue;',
                '\x1b[35m': 'color: magenta;',
                '\x1b[36m': 'color: cyan;',
                '\x1b[37m': 'color: white;',
                '\x1b[40m': 'background-color: black;',
                '\x1b[41m': 'background-color: red;',
                '\x1b[42m': 'background-color: green;',
                '\x1b[43m': 'background-color: yellow;',
                '\x1b[44m': 'background-color: blue;',
                '\x1b[45m': 'background-color: magenta;',
                '\x1b[46m': 'background-color: cyan;',
                '\x1b[47m': 'background-color: white;',
                '\x1b[0m': '' // 重置样式
            };

            // 使用正则替换 ANSI 转义码
            text = text.replace(/\x1b\[([0-9]{1,2})(;[0-9]{1,2})?m/g, (match, p1, p2) => {
                const cssStyle = colorMap[match];
                return cssStyle ? `<span style="${cssStyle}">` : '';
            });

            // 重置字符后加入闭合标签
            text = text.replace(/\x1b\[0m/g, '</span>');

            return text;
        };

        // 将用户输入的命令渲染到控制台
        const renderConsoleOutput = (output) => {
            const consoleOutput = document.getElementById("consoleOutput");
            const convertedOutput = ansiToCss(output);
            const span = document.createElement("span");
            span.innerHTML = convertedOutput;
            consoleOutput.appendChild(span);
            consoleOutput.scrollTop = consoleOutput.scrollHeight; // 滚动到最新输出
        };

        // 颜色名称映射
        const colorNameMap = {
            black: "黑色",
            red: "红色",
            green: "绿色",
            yellow: "黄色",
            blue: "蓝色",
            magenta: "品红",
            cyan: "青色",
            white: "白色",
            bgBlack: "黑色背景",
            bgRed: "红色背景",
            bgGreen: "绿色背景",
            bgYellow: "黄色背景",
            bgBlue: "蓝色背景",
            bgMagenta: "品红背景",
            bgCyan: "青色背景",
            bgWhite: "白色背景"
        };

        // 初始化颜色选择器
        const initColorSelect = () => {
            const colorOptions = document.getElementById("colorOptions");
            const colors = Object.keys(colorize());
            colors.forEach(color => {
                const option = document.createElement("div");
                option.className = "color-option";
                option.textContent = colorNameMap[color];
                option.dataset.color = color;
                option.onclick = () => selectColor(color);
                colorOptions.appendChild(option);
            });
            // 设置默认颜色为红色
            selectColor("red");
        };

        // 处理颜色选择
        let selectedColor = "red";
        const selectColor = (color) => {
            selectedColor = color;
            document.querySelector(".color-select-header span").textContent = colorNameMap[color];
            document.getElementById("colorSelect").classList.remove("open");
        };

        // 切换下拉框显示状态
        document.getElementById("colorSelect").addEventListener("click", (e) => {
            if (!e.target.closest(".color-option")) {
                document.getElementById("colorSelect").classList.toggle("open");
            }
        });

        // 点击其他区域关闭下拉框
        document.addEventListener("click", (e) => {
            if (!e.target.closest(".color-select")) {
                document.getElementById("colorSelect").classList.remove("open");
            }
        });

        // 处理用户输入
        const handleInput = () => {
            const inputField = document.getElementById("consoleInput");
            const inputText = inputField.value.trim();

            if (inputText) {
                try {
                    const args = inputText.split(",").map(arg => arg.trim());
                    const result = colorize(...args)[selectedColor];
                    renderConsoleOutput(result);
                } catch (e) {
                    renderConsoleOutput(`错误: ${e.message}`);
                }
            }

            inputField.value = ""; // 清空输入框
        };

        // 监听键盘回车事件
        document.getElementById("consoleInput").addEventListener("keydown", function (e) {
            if (e.key === "Enter") {
                handleInput();
                e.preventDefault(); // 防止默认的换行行为
            }
        });

        // 初始化颜色选择器和显示提示
        initColorSelect();
        renderConsoleOutput("欢迎使用 Web 控制台！");
        renderConsoleOutput("使用说明：");
        renderConsoleOutput("1. 在输入框中输入要显示的文本，多个文本用逗号分隔");
        renderConsoleOutput("2. 从右侧下拉框选择要应用的颜色");
        renderConsoleOutput("3. 按回车键查看效果");
        renderConsoleOutput("示例：输入 'Hello, World' 并选择 'red' 颜色");
    </script>
</body>

</html>